/**
 * 函数操作
 */
class FunctionFn {

    /**
     * 函数防抖动
     * @param  {Function} fn        [执行的函数]
     * @param  {Number}   delay     [多少秒之后执行]
     * @param  {Boolean}   immediate [是否立即执行]
     * @return {Function}             [函数]
     */
    static debounce(fn, delay, immediate) {
        let timeout;
        return function () {
            let context = this, args = arguments;
            let later = function () {
                timeout = null;
                if (!immediate) fn.apply(context, args);
            };
            let callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, delay);
            if (callNow) fn.apply(context, args);
        };
    }

    /**
     * 函数节流
     * @param  {Function} func  [执行的函数]
     * @param  {Number} delay [多少秒之内执行一次]
     * @return {Function}       [函数]
     */
    static throttle(func, delay) {
        let prev = Date.now();
        return function () {
            let context = this;
            let args = arguments;
            let now = Date.now();
            if (now - prev >= delay) {
                func.apply(context, args);
                prev = Date.now();
            }
        }
    }
}

module.exports = FunctionFn;